package com.yellowpage.wf.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.yellowpage.white.dao.BaseDaoHibernateImpl;
import com.yellowpage.white.dao.QueryAssistantSQL;
import com.yellowpage.wf.data.Context;

public class ContextDaoImpl extends BaseDaoHibernateImpl<Context, Long> implements ContextDao {

	public ContextDaoImpl() {
		super(Context.class);
	}		
	
	public void saveParamsToDb(Map paramMap , Long instanceId){

		if(paramMap == null || paramMap.size() == 0) return;
		
		
		List<Context> contextList = getWorkflowContextByWorkflowInstanceId(instanceId);
		
		for(Context context : contextList){
			
			this.remove(context.getContextId());
		}
		
		Iterator iterator = paramMap.entrySet().iterator();
		while(iterator.hasNext()){
			Map.Entry entry = (Map.Entry)iterator.next();
			Context context = new Context();
			context.setWorkflowId(instanceId);
			context.setParamName((String)entry.getKey());
			context.setDefaultValue((String)entry.getValue());
			//this.baseDao.save(context);
			this.save(context);
		}
	}
	
	public List<Context> getWorkflowContextByWorkflowInstanceId(Long id) {
		return this.getObjectListByConditions("from Context w where w.instanceId = ? ", new Object[]{id});
	}
	
	public String checkIfWorkflowInstanceExisted(String paramName , String paramValue , String type) {
		String sql = " select *  from wf_context wc, wf_workflow_instance i , wf_workflow ww " + 
					 " where i.workflow_instance_id = wc.instance_id and ww.workflow_id = i.workflow_id " +
					 "	and i.status = 'on' ";
					 
  
   
  
		QueryAssistantSQL sqlAssistant = new QueryAssistantSQL(sql)
		    			.addCondition(" and CONTEXT_ID = :contextId ")
					    			.addCondition(" and wc.param_name = :paramName ")
					    			.addCondition(" and wc.param_value = :paramValue ")
					    			.addCondition(" and ww.type= :type ");
					     	
		Map queryMap = new HashMap();
		queryMap.put("paramName", paramName);
		queryMap.put("paramValue", paramValue);
		queryMap.put("type", type);
		//List<Map> resultList = sqlAssistant.query(baseDao.getConnection(), queryMap);
		List<Map> resultList = this.query(sqlAssistant, queryMap);
		
		
		if(resultList.size() > 0) return resultList.get(0).get("WORKFLOW_INSTANCE_ID").toString();
		
		
		return null;
	}
		

}	